﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Collections;
using System.Linq;
using UMC.Web;
using UMC.Wiki.Entities;
using UMC.Web.UI;

namespace UMC.Wiki.Activities
{
    class SubjectAccountActivity : WebActivity
    {

        public override void ProcessActivity(WebRequest request, WebResponse response)
        {
            var identity = this.Context.Token.Identity();
            var userId = UMC.Data.Utility.Guid(this.AsyncDialog("Id", g =>
            {
                if (identity.IsAuthenticated == false)
                {
                    this.Context.Send("Login", true);
                }
                return this.DialogValue(identity.Id.ToString());
            }), true);
            var model = this.AsyncDialog("Model", modKey =>
            {

                var webr = UMC.Web.WebResource.Instance();

                int start = UMC.Data.Utility.IntParse(request.SendValues?["start"], 0);
                UISection ui, ui2;
                var selectIndex = UMC.Data.Utility.IntParse(request.SendValues?["selectIndex"], 0);

                var items = new List<WebMeta>();
                items.Add(new UMC.Web.WebMeta().Put("text", "知识录", "search", "Subs", "Key", "List"));
                items.Add(new UMC.Web.WebMeta().Put("text", "参与项目", "search", "Project", "Key", "List"));
                items.Add(new UMC.Web.WebMeta().Put("text", "个人动态", "search", "Dynamic", "Key", "List"));

                var Keyword = (request.SendValues?["Keyword"] ?? String.Empty);
                if (String.IsNullOrEmpty(Keyword) && selectIndex > -1)
                {
                    Keyword = items[selectIndex]["search"];
                }
                var nextKey = request.SendValues?.Get("NextKey") ?? "Self";// this.AsyncDialog("NextKey", g => this.DialogValue("Header")); ;
                if (start == 0 && String.Equals(nextKey, "Self") && selectIndex == 0)
                {
                    var logoUrl = webr.ImageResolve(request.Url, userId.Value, "1", 4);
                    var attent = DataFactory.Instance().Attention(userId.Value) ?? new Attention();

                    var Discount = new UIHeader.Portrait(logoUrl);

                    ;
                    var user = DataFactory.Instance().Attention(userId.Value);

                    if (userId == identity.Id)
                    {
                        if (user == null)
                        {
                            user = new Attention { Id = identity.Id, Alias = identity.Alias };
                            DataFactory.Instance().Put(user);

                        }
                        else if (String.IsNullOrEmpty(user.Alias))
                        {
                            user.Alias = identity.Alias;
                        }
                    }



                    if (user != null)
                    {
                        if (String.IsNullOrEmpty(user.Alias))
                        {
                            var member = DataFactory.Instance().Search(new ProjectMember { user_id = userId }, 0, out var __, 4).FirstOrDefault();
                            if (String.IsNullOrEmpty(member?.Alias) == false)
                            {
                                DataFactory.Instance().Put(new Attention { Id = user.Id, Alias = member.Alias });

                                Discount.Value(member.Alias);
                            }
                            else
                            {
                                Discount.Value("未知");

                            }
                        }
                        else
                        {
                            Discount.Value(user.Alias);
                        }

                        if (String.IsNullOrEmpty(user.Signature) == false)
                        {
                            Discount.Time(user.Signature);
                            //  Discount.Click
                        }
                        else if (user.Id == identity.Id)
                        {
                            Discount.Time("请设置");

                        }
                    }
                    else
                    {
                        Discount.Value("未设置");
                    }

                    var color = 0x63b359;
                    Discount.Gradient(color, color);
                    var header = new UIHeader();
                    var title = UITitle.Create();

                    title.Title = identity.Id == userId ? "我的知识" : "成员详情";
                    header.AddPortrait(Discount);
                    if (user.Id == identity.Id)
                    {
                        var style = new UIStyle();
                        header.Put("style", style);
                        style.Name("time").Click(new UIClick(request, modKey, "Signature"));
                        style.Name("value").Click(new UIClick(request, modKey, "Alias"));
                    }

                    title.Style.BgColor(color);
                    title.Style.Color(0xfff);

                    ui = UISection.Create(header, title);


                    var uIIcon = new UIIconNameDesc(new UIIconNameDesc.Item('\uF02d', "知识创作", (attent.SubjectTotal ?? 0) + "篇").Color(0x36a3f7), new UIIconNameDesc.Item('\uF19d', "关注项目", (attent.ProjectTotal ?? 0) + "项").Color(0x40c9c6));
                    ui.Add(uIIcon);

                    ui2 = ui.NewSection();
                    if (selectIndex > 0)
                    {

                        ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items).Put("selectIndex", selectIndex)));
                    }
                    else
                    {
                        ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items))); ;

                    }

                }
                else
                {
                    ui2 = ui = UISection.Create();
                    if (start == 0 && String.Equals(nextKey, "List"))
                    {
                        if (selectIndex > 0)
                        {

                            ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items).Put("selectIndex", selectIndex)));
                        }
                        else
                        {
                            ui2.Add(UICell.Create("TabFixed", new UMC.Web.WebMeta().Put("items", items))); ;

                        }
                    }

                }
                ui2.Key = "List";

                int limit = UMC.Data.Utility.IntParse(request.SendValues?["limit"], 25);
                switch (Keyword)
                {
                    default:
                    case "Subs":
                        {
                            int nextIndex;
                            var subjects = DataFactory.Instance().Search(new Subject
                            {
                                Status = 1,
                                user_id = userId
                            }, start, out nextIndex, limit);

                            SubjectUIActivity.Search(ui2, subjects, request.Model, "UIData", false, request.IsApp, request.Url);

                            if (subjects.Length == 0 && start == 0)
                            {
                                ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "尚未有知识资讯").Put("icon", "\uF016")
                                    , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                                ui2.IsNext = false;
                            }
                            else
                            {
                                ui2.StartIndex = nextIndex;
                                ui2.IsNext = nextIndex > 0;
                            }
                        }
                        break;
                    case "Project":
                        {
                            var ids = new HashSet<ulong>();
                            var subMebs = new List<ProjectMember>();
                            // var proReader = new List<ProjectReader>();
                            if (String.Equals(nextKey, "Self"))
                            {
                                UMC.Data.Utility.Each(DataFactory.Instance().ProjectReader(userId.Value).OrderByDescending(r => r.JoinTime), dr =>
                                {

                                    subMebs.Add(new ProjectMember { project_id = dr.project_id, AuthType = WebAuthType.Check });
                                    // proReader.Add(dr);
                                    ids.Add(dr.project_id.Value);
                                });
                            }
                            int nextIndex;
                            UMC.Data.Utility.Each(DataFactory.Instance().Search(new ProjectMember { user_id = userId }, start, out nextIndex, limit).OrderByDescending(r => r.AuthType), dr =>
                             {
                                 subMebs.Add(dr);
                                 ids.Add(dr.project_id.Value);
                             });
                            var projects = new List<Project>();
                            projects.AddRange(DataFactory.Instance().Projects(ids.ToArray()));

                            if (projects.Count > 0)
                            {

                                foreach (var vd in subMebs)
                                {
                                    var p = projects.Find(u => u.Id == vd.project_id);
                                    if (p == null)
                                    {
                                        continue;
                                    }

                                    var cellUI = new UIIconNameDesc(new UIIconNameDesc.Item(webr.ImageResolve(request.Url, p.Id.Value, "1", "4", Utility.TimeSpan(p.ModifiedTime ?? DateTime.Now).ToString()), p.Caption,
                                        String.Format("知识{0}篇", p.SubjectTotal ?? 0))
                                        .Click(request.IsApp ? UIClick.Pager(request.Model, "ProjectUI", new WebMeta().Put("Id", p.Id), true) : new UIClick(request.Model, "ProjectUI", p.Id.ToString())));

                                    if (String.Equals(nextKey, "Self"))
                                    {
                                        switch (vd.AuthType)
                                        {
                                            case WebAuthType.Admin:
                                                cellUI.Button("项目主");
                                                break;
                                            case WebAuthType.User:
                                                cellUI.Button("作家");
                                                break;
                                            case WebAuthType.Check:
                                                cellUI.Button("订阅主");
                                                projects.Remove(p);
                                                break;
                                        }
                                    }
                                    ui2.Add(cellUI);
                                }
                            }

                            ui.StartIndex = nextIndex;
                            ui.IsNext = nextIndex > 0;
                            if (start == 0 && ui2.Length == 0)
                            {

                                ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "尚未有参与项目").Put("icon", "\uF016")
                                    , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                            }
                            ui.SendTo(this.Context);
                            // response.Redirect(ui);
                        }
                        break;

                    case "Dynamic":
                        {

                            var subs = new List<ProjectDynamic>();
                            var projectIds = new List<ulong>();
                            int nextIndex;
                            UMC.Data.Utility.Each(DataFactory.Instance().Search(new ProjectDynamic
                            {
                                user_id = userId
                            }, start, out nextIndex, limit), dr =>
                            {
                                subs.Add(dr);
                                if (dr.project_id.HasValue)
                                {
                                    if (projectIds.Exists(r => r == dr.project_id.Value) == false)
                                    {
                                        projectIds.Add(dr.project_id.Value);
                                    }
                                }

                            });
                            var projects = new List<Project>();
                            if (projectIds.Count > 0)
                            {
                                projects.AddRange(DataFactory.Instance().Projects(projectIds.ToArray()));
                            }

                            foreach (var sub in subs)
                            {
                                var pro = projects.Find(d => d.Id == sub.project_id) ?? new Project();
                                var data = new WebMeta().Put("alias", pro.Caption, "desc", sub.Explain).Put("time", UMC.Data.Utility.GetDate(UMC.Data.Utility.TimeSpan(sub.Time ?? 0)))
                                    .Put("name", sub.Title)
                                    .Put("src", webr.ImageResolve(request.Url, sub.project_id.Value, "1", 5));
                                data.Put("click", new UIClick(request.Model, "Dynamic", new WebMeta().Put("Id", sub.user_id).Put("Time", sub.Time)));
                                var cell = UICell.Create("IconNameDesc", data);

                                cell.Formats.Put("desc", "{time} 在{alias}{desc}");
                                cell.Style.Name("name").Size(14);
                                ui2.Add(cell);
                            }
                            ui.IsNext = nextIndex > 0;
                            if (start == 0 && subs.Count == 0)
                            {

                                ui2.Add("Desc", new UMC.Web.WebMeta().Put("desc", "尚未有个人动态").Put("icon", "\uF016")
                                    , new UMC.Web.WebMeta().Put("desc", "{icon}\n{desc}"), new UIStyle().Align(1).Color(0xaaa).Padding(20, 20).BgColor(0xfff).Size(12).Name("icon", new UIStyle().Font("wdk").Size(60)));
                            }
                            else
                            {
                                ui.StartIndex = nextIndex;
                            }
                        }
                        break;


                }



                ui.SendTo(this.Context, $"{request.Model}.{request.Command}");
            });
            var aUser = DataFactory.Instance().Attention(userId.Value);
            switch (model)
            {
                case "Signature":

                    var Signature = Web.UIDialog.AsyncDialog(this.Context, "Signature", g =>
                    {
                        var selt = new Web.UIFormDialog();
                        selt.Title = "个性签名";
                        selt.AddTextarea("个性签名", "Signature", aUser?.Signature);
                        selt.Submit("确认提交", $"{request.Model}.{request.Command}");
                        return selt;
                    });
                    // var Signature = reset["Signature"];

                    DataFactory.Instance().Put(new Attention { Id = identity.Id.Value, Signature = Signature });
                    this.Context.Send(true);


                    break;
                case "Alias":
                    String Alias = this.AsyncDialog("Alias", a => new UITextDialog() { Title = "修改别名", DefaultValue = aUser?.Alias });

                    DataFactory.Instance().Put(new Attention { Id = identity.Id.Value, Alias = Alias });
                    this.Context.Send(true);



                    break;
            }

        }
    }
}